<template>
  <section>
    <div class="filter-container">
        <common-input type="number" @keyup.enter.native="handleFilter" class="w100" placeholder="商品编号" v-model="listQuery.productNo" />
        <common-input @keyup.enter.native="handleFilter" class="w100 ml10" placeholder="商品名称" v-model="listQuery.keyword" />
        <el-select class="ml10" @change="getCateList(false)" size="mini" v-model="listQuery.parentCateId" placeholder="一级分类">
            <el-option
                    v-for="item in parentCateList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
            </el-option>
        </el-select>
        <el-select size="mini" class="ml10" v-model="listQuery.cateId" placeholder="二级分类">
            <el-option
                    v-for="item in cateList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
            </el-option>
        </el-select>
        <el-button size="mini" class="ml10" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
    </div>
    <el-alert
            v-if="ids&&ids.length>0"
            show-icon>
        <template slot="title">
            <span>已选择 {{ids.length}} 项</span> <el-button @click="clear()" type="text">清空</el-button> <el-button v-if="activeName=='1'" @click="down()" type="text">批量下架</el-button> <el-button v-else-if="activeName=='3'" @click="up()" type="text">批量上架</el-button>
        </template>
    </el-alert>
    <el-table ref="dataTable" :height="tableHeight" :data="list"
                        @sort-change="tblSort"
                style="width: 100%">r">

            <el-table-column label='商品编号'
                prop='id' width='120'></el-table-column>
            <el-table-column align="left" label="商品">
                <template slot-scope="scope">
                    <span>{{scope.row.title}}</span>
                </template>
            </el-table-column>
            <el-table-column align="left" label="" width="120">
                <template slot-scope="scope">
                    <span><img :src="scope.row.listImgUrl" style="width:80px;cursor:pointer;" @click="viewPic(scope.row)" /></span>
                </template>
            </el-table-column>
            <el-table-column label='商品类目' prop='cateName' width='140'>
                <template slot-scope="scope">
                    <span>{{scope.row.parentCateName}}-{{scope.row.cateName}}</span>
                </template>
            </el-table-column>
            <el-table-column label='供货成本' width='140'>
                <template slot-scope="scope">
                <p>¥ {{scope.row.minWholesalePrice}}</p>
                </template>
            </el-table-column>
            <el-table-column label='运费成本' width='140'>
                <template slot-scope="scope">
                <p>¥ {{scope.row.freightPrice}}</p>
                </template>
            </el-table-column>
        <el-table-column label='商品SKU'>
            <template slot-scope="scope">
                <el-button type="text" @click="watchSkuDetail(scope.row)">查看</el-button>
            </template>
        </el-table-column>
      <el-table-column label='状态' prop='isDepotWord'>
      </el-table-column>
            <el-table-column label='选品操作'
                fixed='right'>
                <template slot-scope="scope">
                <el-button v-if='scope.row.isDepot == 1'
                    size='mini'
                    type='danager'
                    :disabled='true'>选品入库</el-button>
                    <el-button v-else
                    size='mini'
                    type='primary'
                    @click="selectShopToStore(scope.row)">选品入库</el-button>
                </template>
            </el-table-column>
    </el-table>
        <div class="pagination-container">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNum" :page-sizes="[20,30, 50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
        </div>

    <el-dialog title="商品SKU信息" :visible.sync="isShowSKUInformtion" :close-on-click-modal="false" width="800px">
        <template v-if="productDetail">
        <div class="shop">
          <div class="shop-top">商品：{{productDetail.title}}</div>
          <el-table :data="productDetail.skuInfo"
            style="width:100%"
            border
            max-height="680"
            :cell-style="tc"
            :header-cell-style="tccolor">
            <el-table-column label='规格名' prop='name'></el-table-column>
            <el-table-column label='规格值' prop='value'></el-table-column>
            <el-table-column label='供货价格' >
            <template slot-scope="scope">
              <p>¥ {{scope.row.wholesalePrice}}</p>
            </template>
            </el-table-column>
            <el-table-column label='商品库存' prop='inventory'></el-table-column>
            <!-- <el-table-column label='* 库存预警值'>
              <template slot-scope="scope">
                <div class="stock">{{scope.row.warning_stock}}</div>
              </template>
            </el-table-column> -->
            </el-table>
        </div>

      </template>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" size="mini" @click="isShowSKUInformtion=false">关闭</el-button>
        </div>
    </el-dialog>
  </section>
</template>

<script>
    import {
        yc_cat_list,
        yc_list,
        yc_detail
    } from '../../api/yc';
    import Viewer from 'viewerjs';
    import 'viewerjs/dist/viewer.css';
    export default {
        components: {
        },
        data() {
            return {
                isShowSKUInformtion: false,
                productDetail: {},
                viewerId: null,
                orderLoading: false,
                tableHeight: 200,
                cateList: [],
                parentCateList:[],
                list: null,
                listLoading: true,
                listQuery: {
                    pageNum: this.$route.query.pageNum || 1,
                    pageSize: this.$route.query.pageSize || 20,
                    agency: undefined,
                    keyword: this.$route.query.keyword,
                    auditStatus: '3',
                    orderCol: "",
                    orderAsc: "",
                    cateId: this.$route.query.cateId,
                    parentCateId: this.$route.query.parentCateId,
                    status: '1',
                    getSaleCount: 1,
                    productNo: this.$route.query.productNo,
                },
                total: null,
                activeName: '1',
                currentId: 0,
                checkLoading: false,
                dialogOrderVisible: false,
                orderForm: {
                    id: 0,
                    orderNum: 0,
                },
                productForm: {
                    id: 0,
                    hasSku: 0,
                    skuInfo: [],
                    inventory: 0,
                },
                dialogStockVisible: false,
                stockLoading: false,
                ids: []
            }
        },
        mounted() {
            const that = this

            window.onresize = () => {

                return (() => {

                    that._getTableHeight()

                })()
            }
        },
        created() {
            this._getTableHeight();
            this.getParentCateList();
            this.getList();
        },
        methods: {
            tc() {
      return "text-align:center; color:#333333; font-size:12px;";
    },
    tccolor() {
      return "text-align:center;background-color:#f5f5f5; font-size:14px;";
    },
            _getTableHeight() {
                this.tableHeight = window.innerHeight - 200
            },
            getList() {
                this.listLoading = true;
                yc_list(this.listQuery).then(response => {
                    this.list = response.data.list;
                    this.total = response.data.total;
                    this.listLoading = false;
                })
            },
            viewPic(row) {
                if(row.imgUrls) {
                    let all_pic = row.imgUrls.split(",");
                    $("#pic_viewer").html("");
                    if(all_pic && all_pic.length > 0) {
                        all_pic.forEach((item, idx)=>{
                            var str  = '<li style="width:100%;">';
                            str += '<img rel-src="' + item + '" src="' + item + '">';
                            str += '</li>';
                            $("#pic_viewer").append(str);
                        })
                    }
                    this.viewerId && this.viewerId.destroy()
                    this.viewerId = new Viewer(document.getElementById('pic_viewer'));
                    $('#pic_viewer').find("img").eq(0).trigger("click")
                }
            },
            getParentCateList() {
                yc_cat_list(0).then((res)=>{
                    this.parentCateList = res.data;
                    this.cateList = []
                }).catch((err)=>{
                    this.parentCateList = []
                    this.cateList = []
                });
            },
            getCateList() {
                this.listQuery.cateId = undefined;
                yc_cat_list(this.listQuery.parentCateId).then((res)=>{
                    this.cateList = res.data;
                }).catch((err)=>{
                    this.cateList = []
                });
            },
            handleFilter() {
                this.listQuery.pageNum = 1;
                this.getList();
            },
            handleSizeChange(val) {
                this.listQuery.pageSize = val;
                this.getList();
            },
            handleCurrentChange(val) {
                this.listQuery.pageNum = val;
                this.getList();
            },
            handleClick(tab, event) {
                this.listQuery.status = this.activeName;
                this.handleFilter();
            // console.log(this.activeName)
            },
            leaveTab(activeName, oldActiveName) {
            // console.log(activeName)
            // return false;
            },
            handleUpdate(row) {
                this.$router.push("/goods_edit?id=" + row.id + "&from=" + encodeURIComponent(this.$router.currentRoute.name)) 
            },
            handleDelete(row) {
                this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        product_delete(row.id)
                            .then(() => {
                                this.$message.success("商品删除成功");
                                this.getList();
                            });
                    }).catch(()=>{});
            },
            handleDetail(row) {
                let {href} = this.$router.resolve({path: '/goods_detail?id=' + row.id});
                window.open(href, '_blank');
            },
            dialogClose() {
                this.$refs.form.resetFields();
            },
            tblSort(d) {
                this.listQuery.orderCol = d.prop;
                this.listQuery.orderAsc = d.order;

                this.handleFilter();
            },
            editOrder(row) {
                this.orderForm.id = row.id;
                this.orderForm.orderNum = row.orderNum;

                // console.log(this.orderForm)
                this.dialogOrderVisible = true;
            },
            okOrder() {
                this.orderLoading = true;
                product_update_order(this.orderForm).then((res)=>{
                    this.orderLoading = false;
                    this.dialogOrderVisible = false;
                    this.$message.success("排序已更新");

                    this.getList();
                }).catch((err)=>{
                    this.orderLoading = false;
                })
            },
            editStock(row) {
                product_detail(row.id).then((res)=>{
                    this.productForm.id = res.data.id;
                    this.productForm.hasSku = res.data.hasSku;
                    this.productForm.inventory = res.data.inventory;
                    this.productForm.skuInfo = res.data.skuInfo;

                    this.dialogStockVisible = true;

                    console.log(this.productForm)
                }).catch((err)=>{

                })
            },
            makeMinStock() {
                let p = 0;
                if(this.productForm.skuInfo && this.productForm.skuInfo.length > 0) {
                    this.productForm.skuInfo.forEach((item)=>{
                        if(item.inventory) {
                            p += Number(item.inventory) || 0
                        }
                    })
                }
                this.productForm.inventory = p;
            },
            okStock() {
                this.stockLoading = true;
                product_update_stock(this.productForm).then((res)=>{
                    this.stockLoading = false;
                    this.dialogStockVisible = false;
                    this.$message.success("库存已更新");

                    this.getList();
                }).catch((err)=>{
                    this.stockLoading = false;
                })
            },
            selectChange(selection) {
                this.ids = [];
                if(selection && selection.length > 0) {
                    selection.forEach((item)=>{
                        this.ids.push(item.id)
                    })
                }
                // console.log(this.ids)
            },
            clear() {
                this.$refs.dataTable.clearSelection();
            },
            up(ids) {
                if(!ids || ids.length < 1) {
                    ids = this.ids;
                }
                this.$confirm('确定上架?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        product_up({
                            ids: ids
                        })
                            .then(() => {
                                this.$message.success("商品上架成功");
                                this.getList();
                            });
                    }).catch(()=>{});
            },
            down(ids) {
                if(!ids || ids.length < 1) {
                    ids = this.ids;
                }
                this.$confirm('确定下架?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        product_down({
                            ids: ids
                        })
                            .then(() => {
                                this.$message.success("商品下架成功");
                                this.getList();
                            });
                    }).catch(()=>{});
            },
            handleUp(row) {
                this.up([row.id]);
            },
            handleDown(row) {
                this.down([row.id]);
            },
            watchSkuDetail(row){
                yc_detail(row.id).then((res)=>{
                    this.productDetail = res.data;
                    this.isShowSKUInformtion = true
                }).catch((err)=>{

                })
            },
            selectShopToStore (row) {
                let url = "/goods_create?no=" + row.id 
                    + "&from=" + encodeURIComponent(this.$router.currentRoute.name)
                    + "&pageSize=" + encodeURIComponent(this.listQuery.pageSize)
                    + "&pageNum=" + encodeURIComponent(this.listQuery.pageNum);
                if(this.listQuery.keyword) {
                    url += "&keyword=" + encodeURIComponent(this.listQuery.keyword);
                }
                if(this.listQuery.productNo) {
                    url += "&productNo=" + encodeURIComponent(this.listQuery.productNo);
                }
                if(this.listQuery.parentCateId) {
                    url += "&parentCateId=" + this.listQuery.parentCateId;
                }
                if(this.listQuery.cateId) {
                    url += "&cateId=" + this.listQuery.cateId;
                }
                this.$router.push(url)
            }
        }
    };
</script>
<style lang="scss" scoped>
</style>
